//求出连通块的个数 - 1即可，注意取-1的时候
class Solution {
public:
    vector<bool> vis;
    vector<vector<int>> g;

    void dfs(int cur)
    {
        vis[cur] = true;
        for(auto& e : g[cur])
        {
            if(vis[e]) continue;
            vis[cur] = true;
            dfs(e);
        }
    }

    int makeConnected(int n, vector<vector<int>>& connections) {
        int m = connections.size();
        if(m < n - 1)
        {
            return -1;
        }

        vis.resize(n);
        g.resize(n);
        for(auto& e : connections)
        {
            g[e[0]].push_back(e[1]);
            g[e[1]].push_back(e[0]);
        }

        int ans = 0;
        for(int i = 0;i < n;i++)
        {
            if(vis[i]) continue;
            dfs(i);
            ans++;
        }
        
        return ans - 1;
    }
};